/**
 * 全局的utils方法
 * @author baoya
 * @since 1.1.0
 * {@link Utils.cflagClick} 绑定事件，用户只要在button a 等后面协商这个标签 cflag:delete
 * {@link getSimpleJson} 与服务器交互
 * {@link getUrlParams} 获取路由后面的参数
 * {@link formatParams} 将路由后面的数据格式化
 */

function getMap() {
    var map = new Map();
    map.set(1001, "请登录后访问");
    map.set(1002, "用户登录异常");
    map.set(1003, "当前用户不存在");
    map.set(1004, "账户名或手机号、密码不能为空");
    map.set(1005, "用户名或密码错误");
    map.set(1006, "注册失败");
    return map;
}

var Utils = {

    //页面事件绑定
    cflagClick: function () {
        $("*[cflag]").unbind("click");
        $("body").on("click", "*[cflag]", function (e) {
            if (!$(this).is(".not-stopPropagation")) {
                e.stopPropagation();
            }
            var target = $(e.target);
            if (!target.parents(".onoffswitch").length) { //过滤掉switch组件
                if ($(this).is("[rightWin=true]") && $(".lgm-common-win-right").length && !$(this).parents("*[op=true]").length) {
                } else {
                    var cid = $(this).attr("cid");
                    if (cid) {
                        fns[$(this).attr("cflag")](cid, $(this));
                    } else {
                        fns[$(this).attr("cflag")]($(this));
                    }
                }
            }
        });
    },

    //提交参数时的时间处理
    paramsDateHandle: function (obj) {
        if (obj) {
            for (var key in obj) {
                var item = obj[key];
                var regDay = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/,
                    regHour = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d)$/,
                    regMin = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d$/;
                if (regDay.test(item)) {
                    obj[key] = item + " 00:00:00";
                } else if (regHour.test(item)) {
                    obj[key] = item + ":00:00";
                } else if (regMin.test(item)) {
                    obj[key] = item + ":00";
                }
            }
            return obj;
        } else {
            alert("请为Utils.paramsDateHandle方法提供参数！");
        }
    },

    //系统中常用的简单的获取json数据的请求
    //var obj = {params: {}, url: "",fn: ,noAsync: error, type: "" , noLayer: false, noErrMsg: false}
    getSimpleJson: function (obj) {
        if (obj) {
            if (!obj.noLayer) {
                obj.index = layer.load("loading...", 3);
            }
            obj.urlFlag = (obj.url.indexOf(".json") > -1 || obj.url.indexOf("http://") > -1 || obj.url.indexOf("https://") > -1);
            obj.url = (obj.url ? (obj.urlFlag ? obj.url : (constant.server_path + obj.url)) : "");
            this.ajax(obj);
        } else {
            layer.msg("请配置参数", {time: 1000, icon: 2});
        }
    },

    /**
     * 如果已有账号，前去登录
     * @param me
     */
    goLogin: function (me) {
        var signInModal = $(me).parents("#signInModal");
        $(signInModal).modal('hide');
        $(signInModal).next().modal('show');
    },

    /**
     * 如果没有账号，前去注册
     * @param me
     */
    goSinIn: function (me) {
        var loginModal = $(me).parents("#loginModal");
        $(loginModal).modal('hide');
        $(loginModal).prev().modal('show');
    },

    /**
     * 登出
     * @param me
     */
    logOut: function () {
        layer.confirm("确认退出", {
            btn: ['确认', '取消']
        }, function (index) {
            Utils.getSimpleJson({
                url: constant.server_path + "/core/member/logout",
                fn: function (data) {
                    if (data) {
                        $("#loginLi").css("display", "block");
                        $("#signInLi").css("display", "block");
                        $("#userInfo").css("display", "none");
                        $("#userInfo").find("span").html("");
                        $("#logOutLi").css("display", "none");
                        layer.close(index);
                    } else {
                        layer.msg("退出失败，请稍后再试", {time: 800, icon: 2});
                    }

                }
            })
        }, function () {
        })
    },

    logIn: function (me) {
        const elements = $("#loginForm").find(".form-control");
        const flag = Utils.validForm(elements);
        const loginPassword = $("#loginForm").find("input[name='loginPassword']").val();
        ///密码至少六位，且有一位英文字母和一个特殊字符
        const passReg = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Za-z])(?=.*[!@#$%^&*? ]).*$/;
        if (!passReg.test(loginPassword)) {
            layer.msg("密码至少六位，且有一位英文字母和一个特殊字符", {time: 800, icon: 2});
            return;
        }
        if (flag) {
            Utils.getSimpleJson({
                url: constant.server_path + "/core/member/login",
                type: "POST",
                params: {
                    phoneOrAccName: $("#loginForm").find("input[name='phoneOrAccName']").val(),
                    password: loginPassword
                },
                fn: function () {
                    Utils.getHeaders();
                }
            })
        }
    },

    /**
     * 注册账号
     * @param me
     */
    signIn: function (me) {
        const elements = $("#signInForm").find(".form-control");
        const flag = Utils.validForm(elements);
        if (flag) {
            const password = $("#signInForm").find("input[name='password']").val();
            const definePassword = $("#signInForm").find("input[name='definePassword']").val();
            const signInType = $("#signInForm").find("input[name='signInType']:selected").val();
            const companyName = $("#signInForm").find("input[name='companyName']").val();
            ///密码至少六位，且有一位英文字母和一个特殊字符
            var passReg = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Za-z])(?=.*[!@#$%^&*? ]).*$/;
            if (!passReg.test(password)) {
                layer.msg("密码至少六位，且有一位英文字母和一个特殊字符", {time: 800, icon: 2});
                return;
            }
            if (password != definePassword) {
                layer.msg("前后密码不一致", {time: 800, icon: 2});
                return;
            }
            if (signInType == 'SIGN_IN_TYPE_ENTERPRISE' && (!companyName || companyName.length <= 0)) {
                layer.msg("企业用户，企业名称不能为空", {time: 800, icon: 2});
                return;
            }
            Utils.getSimpleJson({
                url: constant.server_path + "/core/member/existMember",
                params: {
                    phoneOrAccName: $("#signInForm").find("input[name='phone']").val(),
                    companyName: $("#signInForm").find("input[name='companyName']").val(),
                },
                fn: function (data) {
                    const result = data;
                    if (result == 'EXIST') {
                        layer.confirm("公司名称或手机号已经注册，前去登陆", {
                                btn: ['确认', '取消']
                            }
                            , function () {
                                fns.goLogin($(me).next())
                            }, function () {
                                $(me).parents("#signInModal").modal('hide');
                            }
                        );
                    } else if (result == 'NONENTITY') {
                        $.ajax({
                            url: constant.server_path + "/core/member/signIn",
                            async: true,
                            timeout: 3000,
                            type: "POST",
                            crossDomain: true,
                            cache: false,
                            dataType: "json",//预期服务器返回的数据类型
                            data: $('#signInForm').serialize(),
                            success: function (index) {
                                layer.confirm("注册成功，前去登陆？", {
                                        btn: ['确认', '取消']
                                    }
                                    , function (index) {
                                        layer.close(index);
                                        fns.goLogin($(me).next());
                                    }, function () {
                                        $(me).parents("#signInModal").modal('hide');
                                    }
                                );
                            },
                            error: function () {
                                layer.msg("网络延迟，请稍后继续", {time: 800, icon: 2});
                            }
                        })
                    } else {
                        layer.msg("网络延迟，请稍后继续", {time: 800, icon: 2});
                    }
                }
            })

        }
    },


    //获取请求头信息
    getHeaders: function () {
        var header = {};
        $.ajax({
            url: constant.server_path + "/front/index",
            async: false,
            dataType: 'json',
            timeout: 3000,
            type: "GET",
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            cache: false,
            //这个会导致调用一次，但会返回两个接口。
            // contentType: 'application/text; charset=utf-8;',
            success: function (data, status, xhr) {
                if (xhr.getResponseHeader('name') && xhr.getResponseHeader('session')) {
                    $("#loginLi").css("display", "none");
                    $("#signInLi").css("display", "none");
                    $("#userInfo").css("display", "block");
                    $("#userInfo").find("span").html("欢迎：" + xhr.getResponseHeader('name'));
                    $("#logOutLi").css("display", "block");
                    $("#loginModal").modal('hide');
                }
            },
            fail: function (data) {
                layer.msg("系统繁忙，请稍后再试", {time: 2000, icon: 2})
            }
        });
    },

    //封装ajax
    //var obj = {type: "", params:{},url: "", fn: , noAsync: , error:,}
    ajax: function (obj) {
        $.ajax({
            cache: false,
            type: (obj.type ? obj.type : "GET"),
            crossDomain: true,
            data: Utils.paramsDateHandle($.extend((obj.params ? obj.params : {}), constant.commonParams)),
            url: obj.url,
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            async: (obj.noAsync ? false : true),
            success: function (data) {
                if (!obj.noLayer) {
                    layer.close(obj.index);
                }
                if (data.success) {
                    if (obj.fn && (typeof obj.fn == "function")) {
                        obj.fn(data.resultData, data);
                    }
                } else {
                    var map = getMap();
                    if (data.errorCtx) {
                        if (data.errorCtx) {
                            let code = data.errorCtx.errorCode;
                            if (code == '0002') {
                                window.location.href = "500.html";
                            } else {
                                layer.msg(data.errorCtx.errorMsg, {time: 2000, icon: 2}, function () {
                                    window.location.href = "index.html";
                                });
                            }
                        }
                    }
                }
            },
            error: function (data, status, xhr) {
                if (!obj.noLayer) {
                    layer.close(obj.index);
                }
                var map = getMap();
                let key = data.status;
                if (map.has(key)) {
                    layer.msg(map.get(key), {time: 2000, icon: 2}, function () {
                        window.location.href = "index.html";
                    });
                } else {
                    layer.msg("接口报错了，请检查！！！<br>" + this.url, {time: 2000, icon: 2});
                }

            }
        });
    },

    //获取url路径中的参数
    getUrlParams: function (url) {
        url = url ? url : window.location.href;
        var obj = {};
        if (url.indexOf("?") > -1) {
            url = url.split("?");
            url = url[url.length - 1].split("&");
            for (var i = 0; i < url.length; i++) {
                var item = url[i];
                var param = item.split("=");
                if (obj[param[0]]) {
                    if (obj[param[0]] instanceof Array) {
                        obj[param[0]].push(param[1]);
                    } else {
                        var arr = [];
                        arr.push(obj[param[0]]);
                        arr.push(param[1]);
                        obj[param[0]] = arr;
                    }
                } else {
                    obj[param[0]] = param[1];
                }
            }
        } else {
            console.log("此url:" + url + "无参数");
        }
        return obj;
    },

    //把一个对象格式化为url路径中能用的参数格式
    formatParams: function (obj) {
        obj = $.extend(obj, constant.commonParams);
        var arr = [];
        for (var key in obj) {
            if (obj[key] instanceof Array) {
                for (var i = 0; i < obj[key].length; i++) {
                    arr.push(key + "=" + obj[key][i]);
                }
            } else {
                arr.push(key + "=" + obj[key]);
            }
        }
        return arr.join("&");
    },

    enCrypt: function (password) {
        if (!password) {
            layer.msg("密码不能为空", {time: 800, icon: 2});
        }
        return $.md5(password);
    },

    /**
     * 验证输入框不能为空
     * @param text 这是验证的内容
     * @return boolean
     */
    isNull: function (text, required) {
        return (typeof required == 'undefined' ? false : (required == 'required' && !text) ? true : false);
    },

    /**
     * 验证手机号
     * @param text 这是验证的内容
     * @return boolean
     */
    validPhone: function (text) {
        var reg = /^1(3|4|5|7|8)\d{9}$/;
        return reg.test(text);
    },

    /**
     * 验证邮箱
     * @param text
     * @return {boolean}
     */
    validEmail: function (text) {
        var reg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
        return reg.test(text);
    },

    /**
     * 验证邮箱
     * @param text
     * @return {boolean}
     */
    validUrl: function (text) {
        var reg = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/;
        return reg.test(text);
    },

    /**
     * 验证表单的input select 等
     * @param elements
     */
    validForm: function (elements) {
        var flag = true;
        if (!elements || elements <= 0) {
            layer.msg("表单为空，无法提交", {time: 1000, icon: 2});
            return false;
        }
        $(elements).each(function () {
            const type = $(this).attr("type");
            const required = $(this).attr("required");
            const value = $(this).val();
            const placeholder = $(this).attr("placeholder");
            if (Utils.isNull(value, required)) {
                layer.msg(placeholder + "不能为空", {time: 1000, icon: 2});
                flag = false;
                return;
            }
            if ((type == 'email' && !Utils.validEmail(value)) ||
                (type == 'tel' && !Utils.validPhone(value)) ||
                (type == 'url' && !Utils.validUrl(value))
            ) {
                layer.msg(placeholder + "不符合规则", {time: 1000, icon: 2});
                flag = false;
                return;
            }
        });
        return flag;
    },
    /**
     * 参数包括 url，id
     * @param params={url:"",id:""}
     */
    delete: function (params) {
        $.ajax({
            url: constant.server_path + params.url,
            async: false,
            dataType: 'json',
            timeout: 3000,
            type: "POST",
            crossDomain: true,
            data: {
                _method: "DELETE", //这里是要修改的部分
                id: params['id'],
            },
            xhrFields: {
                withCredentials: true
            },
            cache: false,
            success: function () {
                if (data.success) {
                    layer.msg("删除成功", {time: 800, icon: 1}, function () {
                        fns.search();
                    });
                } else {
                    layer.msg(data.errorCtx.errorMsg, {time: 2000, icon: 2});
                }

            },
            fail: function (data) {
                Utils.failCallback(data)
            }
        });
    },
    /**
     * 失败回调
     * @param obj
     * @param data
     */
    failCallback: function (data) {
        var map = getMap();
        let key = data.status;
        if (map.has(key)) {
            layer.msg(map.get(key), {time: 2000, icon: 2}, function () {
                window.location.href = "index.html";
            });
        } else {
            layer.msg("接口报错了，请检查！！！<br>" + this.url, {time: 2000, icon: 2});
        }
    },

    commonInit: function () {
        Utils.cflagClick();
        Utils.getHeaders();
    }
};

window.Utils = Utils;
Utils.commonInit();